package main

import (
	pb "ihos/ihos"

	tm "github.com/golang/protobuf/ptypes/timestamp"
)

type kefu struct {
	id    int32 //PK
	grxx  int32 //个人信息 => basicinfo PK
	dlxx  int32 //登录信息 => denglu PK
	jlsj  int64 //建立时间，秒
	yy_id int32
}

func (w *kefu) GetFromDB(id int32) error {
	sql := "SELECT id,grxx,dlxx,jlsj,yy_id FROM kefu WHERE id=$1"
	return DBConn.db.QueryRow(sql, id).Scan(&w.id, &w.grxx, &w.dlxx, &w.jlsj, &w.yy_id)
}

func (w *kefu) GetByDlxx(dlxx_id int32) error {
	sql := "SELECT id,grxx,dlxx,jlsj,yy_id FROM kefu WHERE dlxx=$1"
	return DBConn.db.QueryRow(sql, dlxx_id).Scan(&w.id, &w.grxx, &w.dlxx, &w.jlsj, &w.yy_id)
}

func (w *kefu) SaveToDB(id int32) error {
	sql := ""
	var err error
	if id > 0 { //update
		sql = "UPDATE kefu set grxx=$1,dlxx=$2,jlsj=$3,yy_id=$4 where id=$5 RETURNING id"
		err = DBConn.db.QueryRow(sql, w.grxx, w.dlxx, w.jlsj, w.yy_id, w.id).Scan(&w.id)
	} else { //insert
		sql = "INSERT INTO kefu(grxx,dlxx,jlsj,yy_id) VALUES($1,$2,$3,$4) RETURNING id"
		err = DBConn.db.QueryRow(sql, w.grxx, w.dlxx, w.jlsj, w.yy_id).Scan(&w.id)
	}
	return err
}

func (w *kefu) toPB() *pb.KeFuInfoL3 {
	p := &pb.KeFuInfoL3{
		ID:   w.id,
		GRXX: &pb.BasicInfoL1{ID: w.grxx},
		DLXX: &pb.DengLuL2{},
		JLSJ: &tm.Timestamp{Seconds: w.jlsj},
		YY:   &pb.YiYuan{ID: w.yy_id},
	}
	b := &basicinfo{}
	if err := b.GetFromDB(w.grxx); err != nil {
		return nil
	} else {
		p.GRXX = b.toPB()
	}
	d := &denglu{}
	if err := d.GetFromDB(w.dlxx); err != nil {
		return nil
	} else {
		p.DLXX = d.toPB()
	}
	if w.yy_id > 0 {
		y := &yiyuan{}
		if err := y.GetFromDB(w.yy_id); err != nil {
			return nil
		}
		p.YY = y.toPB()
	}
	return p
}

func (w *kefu) fromPB(p *pb.KeFuInfoL3) *kefu {
	w.id = p.GetID()
	w.grxx = p.GetGRXX().GetID()
	w.dlxx = p.GetDLXX().GetJS().GetID()
	w.jlsj = p.GetJLSJ().GetSeconds()
	w.yy_id = p.GetYY().GetID()
	return w
}
